package com.github.tvbox.osc.ui.activity.Media

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentContainerView
import androidx.fragment.app.FragmentManager
import com.github.tvbox.osc.R
import com.github.tvbox.osc.util.FastClickCheckUtil
import com.github.tvbox.osc.util.ImgUtil
import com.orhanobut.logger.Logger
import io.github.source.media.bean.MediaBean

/**
 * @ClassName: MediaPreview
 * @Description: 预 览 主要是标题和海报 （ 预播放窗口 ）)包含了播放窗口（Fragment)
 * @author: huangrongcai
 * @date: 2024/8/22
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class MediaPreview(view: View?) {
    private var mView: View? = view

    /**
     * 播放的窗口
     */
    private var playFragment: PlayFragment? = null
    private var llPlayerFragmentContainer: FragmentContainerView? = null
    private var llPlayerFragmentContainerBlock: View? = null
    private var llPlayerPlace: View? = null
    private var motionLayout: MotionLayout? = null

    /**
     * 播放的海报
     */
    private var ivPoster: View? = null

    /**
     * 标题
     */
    private var tvTitle: TextView? = null

    /**
     * 播放按钮
     */
    private var mTvPlay: View? = null

    /**
     * 预览时的预布局
     */
    private var windowsPreview: ViewGroup.LayoutParams? = null

    /**
     * 全屏布局
     */
    private var windowsFull: ViewGroup.LayoutParams? = null
    private var mFragmentManager: FragmentManager? = null

    /**
     * 是否显示预览(小窗口播放）
     */
    var showPreview = true
    var mediaBean: MediaBean? = null

    companion object {
        @JvmStatic
        fun create(fActivity: FragmentActivity, view: View?): MediaPreview {
            return MediaPreview(view)

        }

        @JvmStatic
        fun create(fragment: Fragment, view: View?): MediaPreview {
            return MediaPreview(view)

        }
    }

    init {
        motionLayout = findViewById(R.id.skin_root_view)
        ivPoster = findViewById<View>(R.id.skin_details_Thumb)
        tvTitle = findViewById<TextView>(R.id.skin_details_Name)
        llPlayerPlace = findViewById<View>(R.id.skin_details_PreviewPlayerPlace)
        llPlayerFragmentContainer =
            findViewById<FragmentContainerView>(R.id.skin_details_PreviewPlayer)
        llPlayerFragmentContainerBlock = findViewById<View>(R.id.skin_details_PreviewPlayerBlock)
        mTvPlay = findViewById<View>(R.id.skin_details_Play)
        setupView()
    }

    private fun setupView() {
        setShowPreviewMode(true)
        setupViewPoster()
        setupViewPlayer()
        setupViewPlayerPlace()
        setupViewBlock()
        addPreviewFragment()
    }

    private fun setupViewPlayerPlace() {
        try {
            llPlayerPlace!!.visibility = if (isShowPreview()) View.VISIBLE else View.GONE
        } catch (e: Exception) {
            Logger.e(e, "")
        }
    }

    private fun setupViewBlock() {
        try {
            llPlayerFragmentContainerBlock!!.visibility = View.VISIBLE
            llPlayerFragmentContainerBlock!!.setOnClickListener { v: View? ->
                FastClickCheckUtil.check(v)
                toggleFullPreview()
            }
        } catch (e: Exception) {
            Logger.e(e, "")
        }
    }

    private fun setupViewPoster() {
        try {
            ivPoster!!.visibility = if (!isShowPreview()) View.VISIBLE else View.GONE
        } catch (e: Exception) {
            Logger.e(e, "" + e.message)
        }
    }

    private fun setupViewPlayer() {
        try {
            mTvPlay?.setOnClickListener { v: View? ->
                FastClickCheckUtil.check(v)
                jumpToPlay()
            }
        } catch (e: Exception) {
            Logger.e(e, "" + e.message)
        }
    }

    fun setFragmentManager(fragmentManager: FragmentManager?) {
        mFragmentManager = fragmentManager
    }

    private fun getFragmentManager(): FragmentManager? {
        if (mFragmentManager == null) {
            if (context() is FragmentActivity) {
                mFragmentManager = (context() as FragmentActivity).supportFragmentManager
            }
            setFragmentManager(mFragmentManager)
        }
        return mFragmentManager
    }

    private fun <T : View?> findViewById(@IdRes id: Int): T? {
        // 尝试从缓存获取，如果缓存中没有，则从视图树中查找并加入缓存
        return if (mView != null) {
            mView!!.findViewById(id)
        } else {
            Logger.e("View is not initialized or null.")
            null
        }
    }

    fun getView(): View? {
        return mView
    }

    private fun jumpToPlay() {
        //去播放（暂停，放大，全屏）
    }

    /**
     * 播放（获取数据并执行播放）
     * @param bean
     */
    private fun startPlay(bean: MediaBean) {
        setShowPreviewMode(true)
        playFragment?.playOnReady(bean)
    }


    /**
     * 设置数据
     *
     * @param mediaBean 媒体对象
     */
    fun setMediaDetails(mediaBean: MediaBean) {
        try {
            this.mediaBean = mediaBean
            if (isShowPreview()) {
                startPlay(mediaBean)
            } else {
                setMediaTitle(mediaBean.vodName)
                setMediaPoster(mediaBean.vodPic)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun setShowPreviewMode(showPreview: Boolean) {
        this.showPreview = showPreview
        if (showPreview) {
            windowsPreview = llPlayerFragmentContainer!!.layoutParams
            llPlayerFragmentContainer!!.visibility = View.VISIBLE
            llPlayerFragmentContainerBlock!!.visibility = View.VISIBLE
            llPlayerPlace!!.visibility = if (isShowPreview()) View.VISIBLE else View.GONE
            ivPoster!!.visibility = if (!isShowPreview()) View.VISIBLE else View.GONE
            tvTitle!!.visibility = if (!isShowPreview()) View.VISIBLE else View.GONE
        } else {
            llPlayerFragmentContainer!!.visibility = View.GONE
            llPlayerFragmentContainerBlock!!.visibility = View.GONE
            llPlayerPlace!!.visibility = if (isShowPreview()) View.VISIBLE else View.GONE
            ivPoster!!.visibility = if (!isShowPreview()) View.VISIBLE else View.GONE
            tvTitle!!.visibility = if (!isShowPreview()) View.VISIBLE else View.GONE
        }
    }

    /**
     * 设置媒体文件标题
     *
     * @param title 标题
     */
    fun setMediaTitle(title: CharSequence) {
        tvTitle?.let { textView ->
            if (textView.text != title) {
                textView.text = title
            }
        }
    }


    /**
     * 设置和显示海报
     */
    fun setMediaPoster(poster: CharSequence) {
        (ivPoster as? ImageView)?.let { imageView ->
            ImgUtil.load(poster.toString(), imageView, 0)
        }
    }

    fun addPreviewFragment() {
        getFragmentManager()?.apply {
            var fragment = findFragmentById(R.id.skin_details_PreviewPlayer)
            if (fragment == null) {
                fragment = PlayFragment()
                playFragment = fragment
                beginTransaction().add(R.id.skin_details_PreviewPlayer, fragment).commit()
            }
            beginTransaction().show(fragment).commitAllowingStateLoss()
        }

    }

    private fun context(): Context {
        return mView!!.context
    }

    fun isShowPreview(): Boolean {
        return showPreview
    }

    fun setPerformPlay(url: String?, headers: Map<String?, String?>?) {
        playFragment?.startPlay(url, headers)
    }

    /**
     * 是不是全屏放
     *
     * @return true 是全屏放
     */
    fun isFullscreen(): Boolean {
        return fullscreen
    }

    /**
     * 设置是不是全屏
     * @param fullscreen true 是全屏； false 否全屏
     */
    private fun setFullscreen(fullscreen: Boolean) {
        this.fullscreen = fullscreen
    }

    private var fullscreen: Boolean = false

    /**
     * 进入全屏播放
     */
    private fun enterFullscreen() {
        //requestFouc
        llPlayerFragmentContainer!!.layoutParams = getFullScreenParams()
        llPlayerFragmentContainerBlock!!.visibility = View.GONE
        motionLayout?.transitionToEnd()

        setFullscreen(true)
        setShowSystemUI(true)
    }

    private fun getFullScreenParams(): ViewGroup.LayoutParams? {
        /*
         * 全屏布局
         */
        if (windowsFull == null) {
            windowsFull = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
        }
        return windowsFull
    }

    /**
     * 退出全屏播放
     */
    private fun exitFullscreen() {
        llPlayerFragmentContainer!!.layoutParams = windowsPreview
        llPlayerFragmentContainerBlock!!.visibility = View.GONE
        motionLayout?.transitionToStart()

        setFullscreen(false)
        setShowSystemUI(false)
    }

    /**
     * 全屏切换处理
     */
    fun toggleFullPreview() {
        val isFullscreen = isFullscreen()
        if (isFullscreen) {
            exitFullscreen()
        } else {
            enterFullscreen()
        }
    }

    fun setShowSystemUI(enable: Boolean) {
        // Hide navbar only when video playing on full window, else show navbar
//        if (enable) {
//            hideSystemUI(false);
//        } else {
//            showSystemUI();
//        }
    }


    private fun onVideo() {
        if (!isFullscreen()) enterFullscreen()
    }

    /**
     * 处理后退事件
     *
     * @return true 已处理，false 未处理
     */
    fun onBackPressed(): Boolean {
        if (isFullscreen()) {
            exitFullscreen()
            return true
        }
        return false
    }

    fun shouldInterceptBack(): Boolean {
        // 根据你的需求判断是否需要拦截返回事件
        val motionLayout = motionLayout ?: return false
        val state = motionLayout.currentState
        if (state == R.id.start) {
            println("当前处于 start 状态")
        } else if (state == R.id.end) {
            println("当前处于 end 状态")
            exitFullscreen()
            return true
        }
        return false
    }

    private fun toggleFullscreenMo() {
        val motionLayout = motionLayout

    }
}